package com.ivanceras.server.services;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map.Entry;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ivanceras.server.dao.DAO_Ad_table;
import com.ivanceras.shared.db.DAO;
import com.ivanceras.shared.db.EMF;
import com.ivanceras.shared.db.EntityManager;
import com.ivanceras.shared.db.Filter;
import com.ivanceras.shared.db.Order;
import com.ivanceras.shared.exception.DatabaseException;
import com.ivanceras.shared.exception.IvancerasServiceException;

public class XmlDataServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -5359445752623415808L;
	public void doGet(HttpServletRequest req, HttpServletResponse res)
	throws ServletException, IOException {

		res.setContentType("text/xml");
		PrintWriter out = res.getWriter();
		String tableName = req.getParameter("table");
		System.out.println("Retrieving data from "+tableName);
		String s_page = req.getParameter("page");
		Integer page = null;
		if(s_page != null){
			page = Integer.parseInt(s_page);
		}
		String s_itemperPage = req.getParameter("items");
		Integer itemPerPage = null;
		if(s_itemperPage != null){
			itemPerPage = Integer.parseInt(s_itemperPage);
		}
		String orderColumn = req.getParameter("orderby");
		String filterColumn = req.getParameter("column");
		String filterOperator = req.getParameter("operator");
		String filterValue = req.getParameter("value");
		try {
			DAO[] daoList = retrieveTableData(tableName, page, itemPerPage, orderColumn, filterColumn, filterOperator, filterValue);
			printXml(out, daoList);
		} catch (IvancerasServiceException e) {
			e.printStackTrace();
		}

	}

	public DAO[] retrieveTableData(String tableName, Integer page, Integer itemPerPage,
			String orderColumn, String filterColumn, String filterOperator, String filterValue) throws IvancerasServiceException {
		EntityManager em = null;
		try {
			em = EMF.get();
			Filter[] tableFilters = {new Filter("lower(tablename)", Filter.EQUAL, tableName.toLowerCase())};
			DAO_Ad_table daoTable = DAO_Ad_table.cast(em.getOne(new DAO_Ad_table(), tableFilters));
			if(daoTable == null){
				throw new IvancerasServiceException("Table Not Found!");
			}

			Order order = orderColumn != null ? new Order(orderColumn) : null;
			filterOperator = filterOperator == null ? Filter.EQUAL : filterOperator;
			Filter filter = filterColumn != null ? new Filter(filterColumn, filterOperator, filterValue) : null;

			DAO[] daoList = DataAPI.retrieveTableData(em, daoTable, page, itemPerPage, order, filter);
			return daoList;
		} catch (DatabaseException e1) {
			e1.printStackTrace();
			throw new IvancerasServiceException();
		}
		finally{
			em.close();
		}
	}

	private static void printXml(PrintWriter out, DAO[] daoList){
		out.print("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
		out.print("\n<data>");
		if(daoList != null && daoList.length > 0){
			String tableName = daoList[0].getModelName();
			tableName = tableName.replace("DAO_", "");
			out.print("\n\t<model name=\""+tableName+"\">");
			for(DAO dao: daoList){
				out.print("\n\t\t<row>");
				HashMap<String, Object> attributes = dao.getProperties();
				for(Entry<String, Object> entry: attributes.entrySet()){
					try {
						Object rvalue = entry.getValue();
						String value = null;
						if(rvalue != null){
							value = new String(rvalue.toString().getBytes(),"UTF-8");
						}
						out.print("\n\t\t\t<"+entry.getKey()+"><![CDATA["+value+"]]></"+entry.getKey()+">");
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
				}
				out.print("\n\t\t</row>");
			}
			out.print("\n\t</model>");
		}
		out.print("\n</data>");
	}

}
